<template>
  <div class="layer-panel">
    <div class="panel-header">
      <span class="panel-title">图层</span>
      <div class="panel-actions">
        <el-tooltip content="删除选中图层" placement="top">
          <el-button icon="el-icon-delete" size="mini" circle :disabled="!canDeleteLayer" @click="deleteSelectedLayer"></el-button>
        </el-tooltip>
        <el-tooltip content="添加图层" placement="top">
          <el-button icon="el-icon-plus" size="mini" circle @click="addLayer"></el-button>
        </el-tooltip>
        <el-tooltip content="选择全部" placement="top">
          <el-button icon="el-icon-check" size="mini" circle></el-button>
        </el-tooltip>
        <el-tooltip content="隐藏" placement="top">
          <el-button icon="el-icon-view" size="mini" circle></el-button>
        </el-tooltip>
        <el-tooltip content="锁定" placement="top">
          <el-button icon="el-icon-lock" size="mini" circle></el-button>
        </el-tooltip>
        <el-tooltip content="移除布局" placement="top">
          <el-button type="text" size="mini" style="color:#409EFF;" :disabled="!canRemoveLayout" @click="removeSelectedLayout">移除布局</el-button>
        </el-tooltip>
        <template v-if="hasNormalLayer">
          <el-button type="text" size="mini" style="color:#409EFF;" @click="addLayout">新建布局</el-button>
        </template>
      </div>
    </div>
    <div v-if="selectedInfo" class="layer-info-panel">
      <template v-if="selectedInfo.isLayout">
        <div>布局全局坐标：X: {{ selectedInfo.left }}, Y: {{ selectedInfo.top }}</div>
        <div>布局尺寸：W: {{ selectedInfo.width }}, H: {{ selectedInfo.height }}</div>
      </template>
      <template v-else-if="selectedInfo.isMulti">
        <div>已选中 {{ selectedInfo.count }} 个图层，可拖入布局</div>
      </template>
    </div>
    <el-tree
      ref="layerTree"
      class="layer-tree"
      :data="layers"
      :props="defaultProps"
      node-key="id"
      :expand-on-click-node="false"
      highlight-current
      draggable
      :allow-drop="allowDrop"
      @node-drop="handleNodeDrop"
      @node-click="handleNodeClick"
      @toggle-visibility="toggleVisibility"
    >
      <template v-slot="{ node, data }">
        <span class="custom-tree-node" :class="{ 'is-layout': data.isLayout }">
          <span class="layer-icons" v-if="!data.isLayout">
            <i
              :class="data.isVisible ? 'el-icon-view' : 'el-icon-view'"
              @click.stop="toggleVisibility(data, $event)"
            ></i>
            <i :class="data.locked ? 'el-icon-lock' : 'el-icon-unlock'" @click.stop="toggleLock(data, $event)"></i>
            <i  class="el-icon-document"></i>
          </span>
          <span class="layer-name-container">
            <i v-if="data.isLayout" class="el-icon-folder" style="margin-right:4px;"></i>
            <span v-if="editingId !== data.id" class="layer-name">{{ data.name }}</span>
            <input
              v-else
              :ref="'editInput-' + data.id"
              v-model="editingName"
              class="edit-input"
              @blur="finishEditing"
              @keyup.enter="finishEditing"
            />
            <i class="el-icon-edit edit-icon" @click="startEditing(data)"></i>
          </span>
          <span class="layer-id">ID {{ node.key.replace(/[^\d]/g, '') }}</span>
          <span v-if="data.fabricObject" class="layer-global-pos">
            (X: {{ getGlobalLeft(data.fabricObject) }}, Y: {{ getGlobalTop(data.fabricObject) }})
          </span>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<script>
export default {
  name: 'LayerControl',
  props: {
    layers: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      editingId: null,
      editingName: '',
      currentSelectedId: null,
      multiSelectedCount: 0
    };
  },
  computed: {
    hasNormalLayer() {
      function findNormal(arr) {
        return arr.some(item => {
          if (item.isLayout !== true) return true;
          if (item.children && item.children.length) return findNormal(item.children);
          return false;
        });
      }
      return findNormal(this.layers);
    },
    canRemoveLayout() {
      // 选中项是layout才可用
      function findLayout(arr, key) {
        for (let item of arr) {
          if ((item.id === key || item.name === key) && item.isLayout === true) return true;
          if (item.children && item.children.length) {
            if (findLayout(item.children, key)) return true;
          }
        }
        return false;
      }
      return this.currentSelectedId && findLayout(this.layers, this.currentSelectedId);
    },
    canDeleteLayer() {
      // 只要有选中项即可
      return !!this.currentSelectedId;
    },
    selectedInfo() {
      // 属性面板信息
      const tree = this.$refs.layerTree;
      if (!tree) return null;
      const selectedNodes = tree.getCheckedNodes ? tree.getCheckedNodes() : [];
      const currentNode = tree.getCurrentNode ? tree.getCurrentNode() : null;
      if (selectedNodes && selectedNodes.length > 1) {
        return { isMulti: true, count: selectedNodes.length };
      }
      if (currentNode && currentNode.fabricObject) {
        const obj = currentNode.fabricObject;
        if (currentNode.isLayout) {
          const rect = obj.getBoundingRect();
          return {
            isLayout: true,
            left: Math.round(rect.left),
            top: Math.round(rect.top),
            width: Math.round(rect.width),
            height: Math.round(rect.height)
          };
        }
      }
      return null;
    }
  },
  methods: {
    addLayer() {
      this.$emit('add-layer');
    },
    addLayout() {
      this.$emit('add-layout');
    },
    deleteLayer(data) {
      this.$emit('delete-layer', data.fabricObject);
    },
    deleteSelectedLayer() {
      if (!this.currentSelectedId) return;
      const node = this.findNodeById(this.layers, this.currentSelectedId);
      if (node) {
        this.$emit('delete-layer', node.fabricObject);
      }
    },
    removeSelectedLayout() {
      if (!this.currentSelectedId) return;
      const node = this.findNodeById(this.layers, this.currentSelectedId);
      if (node && node.isLayout) {
        this.$emit('delete-layer', node.fabricObject);
      }
    },
    findNodeById(arr, id) {
      for (const item of arr) {
        if (item.id === id) return item;
        if (item.children && item.children.length) {
          const found = this.findNodeById(item.children, id);
          if (found) return found;
        }
      }
      return null;
    },
    moveLayerUp(data) {
      this.$emit('move-layer-up', data.fabricObject);
    },
    moveLayerDown(data) {
      this.$emit('move-layer-down', data.fabricObject);
    },
    handleNodeClick(data) {
      this.currentSelectedId = data.id;
      this.$emit('select-layer', data.fabricObject);
    },
    allowDrop(draggingNode, dropNode, type) {
      if (!dropNode.data.isLayout && type === 'inner') {
        return false;
      }
      if (dropNode.data.isLayout && type === 'inner') {
        return !draggingNode.data.isLayout;
      }
      return true;
    },
    handleNodeDrop(draggingNode, dropNode, dropType) {
      if (dropType === 'inner') {
        this.$emit('group-layer', {
          layer: draggingNode.data.fabricObject,
          group: dropNode.data.fabricObject
        });
      } else {
        this.$emit('reorder-layer', {
          layer: draggingNode.data.fabricObject,
          targetLayer: dropNode.data.fabricObject,
          dropType: dropType
        });
      }
    },
    startEditing(data) {
      this.editingId = data.id;
      this.editingName = data.name;
      this.$nextTick(() => {
        const inputRef = this.$refs['editInput-' + data.id];
        if (inputRef) {
          inputRef.focus();
        }
      });
    },
    finishEditing() {
      if (this.editingId) {
        this.$emit('update-layer-name', { id: this.editingId, newName: this.editingName });
        this.editingId = null;
        this.editingName = '';
      }
    },
    toggleVisibility(data, event) {
      if (event) event.stopPropagation();
      this.$emit('toggle-layer-visibility', { id: data.id });
    },
    toggleLock(data, event) {
      if (event) event.stopPropagation();
      this.$emit('toggle-layer-lock', { id: data.id, locked: !data.locked });
    },
    getGlobalLeft(fabricObject) {
      if (!fabricObject) return 0;
      return Math.round(fabricObject.getBoundingRect().left);
    },
    getGlobalTop(fabricObject) {
      if (!fabricObject) return 0;
      return Math.round(fabricObject.getBoundingRect().top);
    }
  }
};
</script>

<style scoped>
.layer-panel {
  background: #fff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  padding: 0;
  font-size: 14px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px 4px 12px;
  border-bottom: 1px solid #ebeef5;
}
.panel-title {
  font-weight: bold;
  color: #333;
}
.panel-actions {
  display: flex;
  align-items: center;
  gap: 4px;
}
.layer-tree {
  padding: 8px 0;
  flex: 1;
  overflow: auto;
}
.el-tree-node__content {
  height: 36px !important;
  box-sizing: border-box;
  display: flex !important;
  align-items: center !important;
  padding: 0 !important;
}
.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  background: transparent;
  box-sizing: border-box;
  height: 40px;
  border-bottom: 1px solid #f5f5f5;
}
.custom-tree-node.is-layout {
  /* background: #f5f7fa; */
}
.custom-tree-node:not(.is-layout) {
  /* background: #fff; */
}
.layer-icons {
  min-width: 48px;
  display: flex;
  align-items: center;
  gap: 2px;
  color: #909399;
  height: 100%;
}
.layer-name-container {
  flex-grow: 1;
  display: flex;
  align-items: center;
  margin-left: 4px;
}
.layer-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.edit-icon {
  display: none; /* Hide by default */
  margin-left: 8px;
  cursor: pointer;
  color: #409EFF;
}
.custom-tree-node:hover .edit-icon {
  display: inline; /* Show on hover */
}
.edit-input {
  flex-grow: 1;
  border: 1px solid #409EFF;
  border-radius: 3px;
  padding: 2px 4px;
}
.layer-id {
  color: #bbb;
  font-size: 12px;
  margin-left: 8px;
  min-width: 48px;
  text-align: right;
  display: flex;
  align-items: center;
  height: 100%;
}
/* 强制高亮选中项，优先级最高 */
::v-deep .el-tree-node.is-current > .el-tree-node__content {
  background: #b0cbed !important;
  z-index: 10;
}
::v-deep .el-tree-node.is-current .custom-tree-node {
  /* background: #f2f2f2 !important; */
}
::v-deep .el-tree-node__content{
  height: 40px;
}
.el-icon-hide {
  color: #c0c4cc;
}
.custom-tree-node.is-layout .layer-name-container {
  justify-content: flex-start;
}
.custom-tree-node.is-layout .layer-name {
  text-align: left;
}
.layer-global-pos {
  color: #888;
  font-size: 12px;
  margin-left: 8px;
}
.layer-info-panel {
  background: #f7f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 8px 12px;
  font-size: 13px;
  color: #333;
}
</style> 